package ds_industry_2025.ds.ds_02.T1

import org.apache.hudi.DataSourceWriteOptions._
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}
/*
      1、抽取shtd_store库中user_info的增量数据进入Hudi的ods_ds_hudi库中表user_info。根据ods_ds_hudi.user_info表
      中operate_time或create_time作为增量字段(即MySQL中每条数据取这两个时间中较大的那个时间作为增量字段去和ods里的这两个字
      段中较大的时间进行比较)，只将新增的数据抽入，字段名称、类型不变，同时添加分区，若operate_time为空，则用create_time填充，
      分区字段为etl_date，类型为String，且值为当前比赛日的前一天日期（分区字段格式为yyyyMMdd）。id作为primaryKey，
      operate_time作为preCombineField。使用spark-shell执行show partitions ods_ds_hudi.user_info命令，将结果截
      图粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下；
 */
object t1 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t1")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val conn=new Properties()
    conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")

    val day=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)

    val hdfs_path="hdfs://192.168.40.110:9000/user/hive/warehouse/ods_ds_hudi.db/user_info"

    val max_time = spark.read.format("hudi").load(hdfs_path)
      .agg(max(greatest(col("create_time"), col("operate_time"))))
      .collect()(0).get(0).toString

    println(max_time)

    spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false","user_info",conn)
      .withColumn(
        "operate_time",
        when(col("operate_time").isNull,col("create_time")).otherwise(col("operate_time"))
      )
      .where(
        greatest(col("create_time"),col("operate_time")) > lit(max_time).cast("timestamp")
      )
      .withColumn("etl_date",lit(yesterday))
      .write.format("hudi").mode("append")
      .options(getQuickstartWriteConfigs)
      .option(RECORDKEY_FIELD.key(),"id")
      .option(PRECOMBINE_FIELD.key(),"operate_time")
      .option(PARTITIONPATH_FIELD.key(),"etl_date")
      .option("hoodie.table.name","user_info")
      .save(hdfs_path)

    spark.close()
  }

}
